Popular Searches
Popular Course Categories
Popular Courses

Handling Multiple Inputs

Handling Multiple Inputs

React Forms

Handling Multiple Inputs in React JS

Handling Multiple Inputs in React JS means managing multiple form fields, such as name, email, phone number, password, age, and course selection, within a single React component. React developers commonly use the useState() Hook, the onChange event, and the name attribute to manage these input fields efficiently.

Course Link: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. Learning Objectives

After completing this topic, you will be able to:

  • Understand how to manage multiple input fields in React.
  • Use the useState() Hook to store form data.
  • Handle multiple inputs using a single onChange function.
  • Understand the role of the name attribute.
  • Update objects in React state without losing existing values.
  • Handle text inputs, email fields, checkboxes, radio buttons, and dropdowns.
  • Implement form validation, submission, and reset functionality.

2. What Is Handling Multiple Inputs?

Handling multiple inputs means collecting and managing values from several input fields in a form. Instead of creating separate event handlers for every field, React allows developers to manage related values through a single state object and a shared event handler.

For example, a student registration form may contain:

  • Full Name
  • Email Address
  • Phone Number
  • Password
  • Course Selection
  • Terms and Conditions Checkbox

Each field stores different information, but all fields can be managed within the same React component.

Example: Multiple Input Fields

function RegistrationForm() {
  return (
    <form>
      <input type="text" placeholder="Enter your name" />
      <input type="email" placeholder="Enter your email" />
      <input type="tel" placeholder="Enter your phone number" />
      <button type="submit">Register</button>
    </form>
  );
}
export default RegistrationForm;

Explanation: This example creates multiple fields, but it does not store their values in React state. To manage the values and respond to user input, we can use controlled components.


3. Managing Multiple Inputs Using useState()

The useState() Hook allows a functional component to store and update data. For multiple related inputs, we can store all the field values inside one object.

Syntax

const [formData, setFormData] = useState({
  name: "",
  email: "",
  phone: ""
});

Explanation

  • formData contains the current values of all fields.
  • setFormData() updates the form state.
  • name, email, and phone are properties of the state object.
  • Each input can read its value from the corresponding property.

This approach keeps related form data organized and makes it easier to manage larger forms.


4. Using the name Attribute

The name attribute identifies an input field. When several fields share the same change handler, the handler can use this attribute to determine which state property should be updated.

Example

<input
  type="text"
  name="name"
  placeholder="Enter your name"
/>
<input
  type="email"
  name="email"
  placeholder="Enter your email"
/>

Here, the first input has the name name, while the second input has the name email. These names can correspond to properties in the React state object.

Important: The input's name attribute must match the state object's property name when using a generic change handler.


5. Handling Multiple Inputs with a Single onChange Handler

A shared onChange handler can manage multiple fields. It reads the changed field's name and value, then updates the matching property in the state object.

Complete Example

import { useState } from "react";
function RegistrationForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: ""
  });
  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((previousData) => ({
      ...previousData,
      [name]: value
    }));
  };
  return (
    <form>
      <label htmlFor="name">Full Name:</label>
      <input
        id="name"
        type="text"
        name="name"
        value={formData.name}
        onChange={handleChange}
      />
      <label htmlFor="email">Email:</label>
      <input
        id="email"
        type="email"
        name="email"
        value={formData.email}
        onChange={handleChange}
      />
      <label htmlFor="phone">Phone Number:</label>
      <input
        id="phone"
        type="tel"
        name="phone"
        value={formData.phone}
        onChange={handleChange}
      />
      <h3>Form Data</h3>
      <pre>{JSON.stringify(formData, null, 2)}</pre>
    </form>
  );
}
export default RegistrationForm;

How It Works

  1. useState() creates an object containing the initial field values.
  2. Each input uses the name attribute to identify its corresponding state property.
  3. The onChange event calls handleChange() whenever the user changes an input.
  4. event.target identifies the input that triggered the event.
  5. name and value are extracted from the event target.
  6. The spread operator preserves existing form values.
  7. The computed property [name] updates only the field that changed.

6. Understanding the Spread Operator

The spread operator (...) is important when updating objects in React state. React state should be treated as immutable, so create a new object rather than modifying the existing state object directly.

Example

setFormData((previousData) => ({
  ...previousData,
  [name]: value
}));

Suppose the existing state is:

{
  name: "Rahul",
  email: "[email protected]",
  phone: "9876543210"
}

If the user changes the email, the updated state might be:

{
  name: "Rahul",
  email: "[email protected]",
  phone: "9876543210"
}

The name and phone number remain unchanged because the spread operator preserves the other properties.

What Happens Without the Spread Operator?

setFormData({
  [name]: value
});

This creates an object containing only the changed property, so the other form properties are lost. For this reason, preserve the existing properties when updating part of an object.


7. Handling Different Types of Inputs

7.1 Text Inputs

Text inputs are used to collect information such as names, usernames, and addresses.

<input
  type="text"
  name="name"
  value={formData.name}
  onChange={handleChange}
/>

7.2 Email Inputs

Email inputs collect email addresses and can use browser validation through the type="email" attribute.

<input
  type="email"
  name="email"
  value={formData.email}
  onChange={handleChange}
  required
/>

7.3 Number Inputs

Number inputs can collect numeric information such as age or quantity. The value obtained from event.target.value is still a string, so convert it when performing numeric calculations.

<input
  type="number"
  name="age"
  value={formData.age}
  onChange={handleChange}
/>

7.4 Password Inputs

Password inputs visually conceal the entered characters. This does not encrypt the value or make client-side storage secure.

<input
  type="password"
  name="password"
  value={formData.password}
  onChange={handleChange}
/>

7.5 Dropdown Inputs

A dropdown allows users to select an option from a list.

<select
  name="course"
  value={formData.course}
  onChange={handleChange}
>
  <option value="">Select a course</option>
  <option value="React JS">React JS</option>
  <option value="Flutter">Flutter</option>
  <option value="Figma">Figma</option>
</select>

7.6 Textarea Inputs

Textareas are used for multiline content such as comments, descriptions, and feedback.

<textarea
  name="message"
  value={formData.message}
  onChange={handleChange}
  placeholder="Enter your message"
/>

8. Handling Checkboxes and Radio Buttons

Checkboxes and radio buttons need special handling because their selection state is represented by the checked property rather than the text input's value property.

8.1 Handling a Checkbox

const handleChange = (event) => {
  const { name, value, type, checked } = event.target;
  setFormData((previousData) => ({
    ...previousData,
    [name]: type === "checkbox" ? checked : value
  }));
};

Use the following input with the handler above:

<label>
  <input
    type="checkbox"
    name="acceptedTerms"
    checked={formData.acceptedTerms}
    onChange={handleChange}
  />
  I accept the terms and conditions
</label>

When the checkbox is selected, checked becomes true. When it is deselected, checked becomes false.

8.2 Handling Radio Buttons

Radio buttons allow the user to select one option from a group. Use the same name for related radio buttons and store the selected option in state.

<label>
  <input
    type="radio"
    name="gender"
    value="Male"
    checked={formData.gender === "Male"}
    onChange={handleChange}
  />
  Male
</label>
<label>
  <input
    type="radio"
    name="gender"
    value="Female"
    checked={formData.gender === "Female"}
    onChange={handleChange}
  />
  Female
</label>

9. Form Validation with Multiple Inputs

Form validation checks whether the user has entered the required information in the correct format. Validation can use HTML attributes, custom JavaScript conditions, and server-side checks.

Example: Basic Required-Field Validation

import { useState } from "react";
function ContactForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: ""
  });
  const [error, setError] = useState("");
  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((previousData) => ({
      ...previousData,
      [name]: value
    }));
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    if (!formData.name.trim() || !formData.email.trim()) {
      setError("Please fill in all required fields.");
      return;
    }
    setError("");
    alert("Form submitted successfully!");
  };
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input id="name" name="name" value={formData.name}
        onChange={handleChange} required />
      <label htmlFor="email">Email:</label>
      <input id="email" name="email" type="email"
        value={formData.email} onChange={handleChange} required />
      {error && <p role="alert">{error}</p>}
      <button type="submit">Submit</button>
    </form>
  );
}
export default ContactForm;

Explanation: The form checks whether the name and email are empty. The email input also uses browser validation. In a production application, additional validation and server-side verification may be necessary.


10. Submitting Multiple Input Values

The onSubmit event handles form submission. Use event.preventDefault() when the form should be processed by React without the browser's default page navigation.

const handleSubmit = (event) => {
  event.preventDefault();
  console.log("Submitted form:", formData);
};

Attach the function to the form:

<form onSubmit={handleSubmit}>
  {/* Add your input fields here */}
  <button type="submit">Submit</button>
</form>

In this example, the values are logged for demonstration. To save form data permanently, connect the form to an appropriate backend or API. Avoid logging sensitive information such as passwords.


11. Resetting Multiple Input Fields

To reset a controlled form, set the state back to its initial values.

const initialData = {
  name: "",
  email: "",
  phone: ""
};
const [formData, setFormData] = useState(initialData);
const handleReset = () => {
  setFormData(initialData);
};

Use a reset button:

<button type="button" onClick={handleReset}>
  Reset Form
</button>

For more complex forms, reset all related state, including validation messages and submitted results, if necessary.


12. Complete Practical Project: Student Registration Form

This project demonstrates how to manage multiple inputs using a single state object and one shared event handler. It includes name, email, phone number, course selection, terms acceptance, validation, submission, and reset functionality.

Complete Code

import { useState } from "react";
const initialData = {
  name: "",
  email: "",
  phone: "",
  course: "",
  acceptedTerms: false
};
function StudentRegistration() {
  const [formData, setFormData] = useState(initialData);
  const [error, setError] = useState("");
  const [submittedData, setSubmittedData] = useState(null);
  const handleChange = (event) => {
    const { name, value, type, checked } = event.target;
    setFormData((previousData) => ({
      ...previousData,
      [name]: type === "checkbox" ? checked : value
    }));
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    if (
      !formData.name.trim() ||
      !formData.email.trim() ||
      !formData.phone.trim() ||
      !formData.course
    ) {
      setError("Please complete all required fields.");
      return;
    }
    if (!formData.acceptedTerms) {
      setError("Please accept the terms and conditions.");
      return;
    }
    setError("");
    setSubmittedData({ ...formData });
  };
  const handleReset = () => {
    setFormData(initialData);
    setError("");
    setSubmittedData(null);
  };
  return (
    <div>
      <h2>Student Registration</h2>
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">Full Name:</label>
        <input id="name" name="name" value={formData.name}
          onChange={handleChange} required />
        <label htmlFor="email">Email Address:</label>
        <input id="email" name="email" type="email"
          value={formData.email} onChange={handleChange} required />
        <label htmlFor="phone">Phone Number:</label>
        <input id="phone" name="phone" type="tel"
          value={formData.phone} onChange={handleChange} required />
        <label htmlFor="course">Select Course:</label>
        <select id="course" name="course" value={formData.course}
          onChange={handleChange} required>
          <option value="">Choose a course</option>
          <option value="React JS">React JS</option>
          <option value="Flutter">Flutter</option>
          <option value="Figma">Figma</option>
        </select>
        <label>
          <input type="checkbox" name="acceptedTerms"
            checked={formData.acceptedTerms} onChange={handleChange} />
          I accept the terms and conditions
        </label>
        {error && <p role="alert">{error}</p>}
        <button type="submit">Register</button>
        <button type="button" onClick={handleReset}>Reset</button>
      </form>
      {submittedData && (
        <div>
          <h3>Registration Details</h3>
          <p>Name: {submittedData.name}</p>
          <p>Email: {submittedData.email}</p>
          <p>Phone: {submittedData.phone}</p>
          <p>Course: {submittedData.course}</p>
        </div>
      )}
    </div>
  );
}
export default StudentRegistration;

Project Features

  • Manages multiple fields with one state object.
  • Uses a shared handleChange() function.
  • Handles checkbox state using a boolean value.
  • Validates required fields and terms acceptance.
  • Displays submitted details after successful validation.
  • Resets the form and clears error and submission state.

Note: This is a client-side learning project. It does not send data to a server or save registrations in a database.


13. Best Practices for Handling Multiple Inputs

  • Use one state object for related fields when it makes the form easier to maintain.
  • Use meaningful and unique field names that match the state properties.
  • Preserve existing state properties with the spread operator when updating an object.
  • Use a functional state update when deriving new state from previous state.
  • Use checked for controlled checkboxes and radio buttons.
  • Initialize controlled text inputs with strings, checkboxes with booleans, and other values with appropriate initial types.
  • Associate labels with inputs using htmlFor and id.
  • Use clear validation messages and accessible error announcements.
  • Use explicit button types inside forms.
  • Validate data on the server before accepting or storing it.
  • Keep passwords and other sensitive information out of logs and unnecessary state persistence.

14. Common Mistakes and Solutions

Mistake Solution
Forgetting the name attribute Add a name that matches the corresponding state property.
Updating only one property without preserving the others Use ...previousData when creating the updated object.
Using the same name for unrelated fields Give each independent field a unique name.
Using value for checkbox selection Use checked and read event.target.checked.
Forgetting to bind the change handler Add onChange={handleChange} to each controlled input.
Using undefined values in controlled inputs Initialize state with suitable values such as empty strings.
Assuming numeric input values are numbers Convert the input string to a number when needed.
Expecting form submission to save data automatically Connect the form to a backend or API if persistent storage is required.

15. Interview Questions and Answers

Q1. What does handling multiple inputs mean in React?

It means managing values from several form fields within a React component, usually with state and event handlers.

Q2. How can multiple input fields be managed using one state object?

Store the fields as properties in an object and update the appropriate property using the field's name attribute.

Q3. Why is the name attribute important?

It identifies which input changed and helps the shared change handler update the corresponding state property.

Q4. What is the purpose of the spread operator?

It copies existing object properties into a new object so that updating one field does not remove the other fields.

Q5. What does event.target.value return?

It returns the current value of the input, typically as a string.

Q6. How do you handle a checkbox with a shared event handler?

Read event.target.checked and use it when the target input type is a checkbox.

Q7. Why should React state objects not be mutated directly?

React state should be updated immutably so that state changes are represented by new values and React can process updates predictably.

Q8. How can you reset multiple inputs?

Set the state object back to its initial values and clear any related validation or submission state when needed.

Q9. What is a controlled component?

A controlled input is an input whose current value or checked state is managed by React state.

Q10. How do you submit multiple input values?

Handle the form's onSubmit event, validate the state object, and then process the data locally or send it to a backend.


16. Practice Exercises

  1. Create a form with name, email, and phone fields using a single state object.
  2. Use one handleChange() function for all text inputs.
  3. Add a dropdown to select a course and display the selected value.
  4. Add a checkbox for accepting terms and conditions.
  5. Create a form with radio buttons for selecting a preferred learning mode.
  6. Validate that required fields are completed before submission.
  7. Add a reset button that restores all fields to their initial values.
  8. Build a student registration form and display the submitted data.

17. Quick Revision Checklist

  • Understand the purpose of handling multiple inputs.
  • Know how to use useState() for form data.
  • Understand the name attribute and shared onChange handler.
  • Know how to update a state object using the spread operator.
  • Handle text, email, number, dropdown, checkbox, and radio inputs.
  • Implement validation, submission, and reset functionality.
  • Understand controlled components and immutable state updates.
  • Follow accessibility and data-validation best practices.

18. Conclusion

Handling Multiple Inputs is an important React JS concept for building registration forms, login pages, contact forms, checkout screens, and other interactive applications. Using useState(), the name attribute, a shared onChange handler, and the spread operator makes it easier to manage form data in a structured and maintainable way.

Explore more React JS concepts through JustAcademy React JS Training Course or register for a demo through Register for React JS Course Demo.

whatsapp